package cn.itcast.bos.web.action;

import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.UserService;
import cn.itcast.bos.web.action.common.BaseAction;
import com.opensymphony.xwork2.ActionContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.objectweb.asm.tree.TryCatchBlockNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.util.List;

@ParentPackage(value="json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class UserAction extends BaseAction<User> {

	@Autowired
	private UserService userService;

	@Action(value = "user_login",results = {@Result(name = SUCCESS,type = "redirect",location = "/index.html"),
												@Result(name = ERROR,type = "redirect",location = "/login.html")})
	public String login(){
		// 用户名和密码 都保存在model中
		// 基于shiro实现登录
		String username = model.getUsername();
		String password = model.getPassword();
		// 传统开发（非shiro），使用登录名和密码查询数据库，返回User，使用User判断当前用户是否登录成功
		// 使用Shiro开发登录认证：Subject（存储当前用户）-->SecurityMangerment-->Realm（操作数据库Dao）
		// 获取主题用户
		Subject subject = SecurityUtils.getSubject();
		// 存储登录名和密码（将登录名和密码传递给Realm）
		UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
		// 登录
		// 如果登录名和密码输入正确，不会抛出异常
		try {
			subject.login(usernamePasswordToken);
			return SUCCESS;
		} catch (AuthenticationException e) {
			if(e instanceof UnknownAccountException){
				System.out.println("用户名输入有误！！！！");
			}
			if(e instanceof IncorrectCredentialsException){
				System.out.println("密码输入有误！！！！");
			}
			// 如果登录名或者密码输入有误，抛出异常
			//e.printStackTrace();
			return ERROR;
		}
	}

	@Action(value = "user_logout",results = {@Result(name = SUCCESS,type = "redirect",location = "login.html" )})
	public String logout(){
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return SUCCESS;
	}

	@Action(value = "user_list", results = { @Result(name = "success", type = "json") })
	public String list() {
		// 调用业务层 ，返回 用户列表
		List<User> users = userService.findAll();
		ActionContext.getContext().getValueStack().push(users);
		return SUCCESS;
	}

	// 属性驱动
	private String[] roleIds;

	public void setRoleIds(String[] roleIds) {
		this.roleIds = roleIds;
	}

	@Action(value = "user_save", results = { @Result(name = "success", type = "redirect", location = "pages/system/userlist.html") })
	public String save() {
		// 调用业务层
		userService.saveUser(model, roleIds);
		return SUCCESS;
	}


}













